package com.mission.schedule.clock

import com.mission.schedule.applcation.App
import com.mission.schedule.bean.RepeatBean
import java.text.SimpleDateFormat
import java.util.*

class RepeatDateUtil {

    companion object {

        val day_format = SimpleDateFormat("yyyy-MM-dd")
        val time_format = SimpleDateFormat("yyyy-MM-dd HH:mm")
        val simpleDateFormat = SimpleDateFormat("HH:mm")
        @JvmStatic
        open var sevenWorkTime = arrayListOf<String>()

        /**
         * @param date  重复时间
         * @param type  重复类型
         * @param repTypeParameter 重复大写时间
         * @param yearType  每年区分，0 公历 1 农历
         */
        @JvmStatic
        open fun dateTimeToChildAlarmDate(dateTime: String, type: Int, repTypeParameter: String = "", yearType: String = "", repDisplayTime: String = "0"): RepeatBean {
            var repeatBean = RepeatBean()
            when (type) {
                1 -> repeatBean = toDayChildAlarmDate(dateTime, repDisplayTime)
                2 -> repeatBean = weekChildAlarmDate(dateTime, repTypeParameter, repDisplayTime)
                3 -> repeatBean = monthChildAlarmDate(dateTime, repTypeParameter, repDisplayTime)
                4, 6 -> repeatBean = yearChildAlarmDate(dateTime, repTypeParameter, yearType, repDisplayTime)
                5 -> repeatBean = workDayChildAlarmDate(dateTime, repDisplayTime)
            }
//            Log.e("RepeatDateUtil", repeatBean.repNextCreatedTime)

            return repeatBean
        }


        /**
         * 每天
         */
        fun toDayChildAlarmDate(dateTime: String, repDisplayTime: String): RepeatBean {
            var repeatBean = RepeatBean()
            try {
                val calender = Calendar.getInstance()

                var now = simpleDateFormat.format(Date(System.currentTimeMillis()))
                val time_form = simpleDateFormat.parse(now).time
                var time_to = simpleDateFormat.parse(dateTime).time
                if (time_to <= time_form) {
                    calender.add(Calendar.DATE, +1)
                }
                var datetime = dateTime
                if (repDisplayTime == "0") {
                    datetime = "23:59"
                }
                repeatBean.repNextCreatedTime = "${day_format.format(calender.time)} $datetime"
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return repeatBean
        }

        /**
         * 工作日，跳过节假日，一条子记事，15条闹钟
         */
        fun workDayChildAlarmDate(dateTime: String,repDisplayTime: String): RepeatBean {
            var repeatBean = RepeatBean()
            sevenWorkTime.clear()
            try {
                val calender = Calendar.getInstance()
                val now_day = calender.get(Calendar.DATE).toString()
                var now = simpleDateFormat.format(Date(System.currentTimeMillis()))
                val time_form = simpleDateFormat.parse(now).time
                var time_to = simpleDateFormat.parse(dateTime).time

                //获取明天之后15天不含节假日
                val list = App.getDBcApplication().queryNOTHOLIDAY(day_format.format(calender.time), 1) as  List<Map<String, String>>
                var newlist = ArrayList<String>()
                list.forEach {
                    if (newlist.size < 16) {
                        if (it["isno"] == "0" && (it["week"] != "星期日" && it["week"] != "星期六")) {
                            newlist.add(it["calender"]!!)
                        }
                    }
                }
                var datetime = dateTime
                if (repDisplayTime == "0") {
                    datetime = "23:59"
                }
                //今天不是节假日
                if (newlist.isNotEmpty()) {
                    when {
                        newlist[0].substring(8, newlist[0].length) == now_day -> {
                            if (time_to <= time_form) {
                                repeatBean.repNextCreatedTime = "${newlist[1]} $datetime"
                            } else {
                                repeatBean.repNextCreatedTime = "${day_format.format(calender.time)} $datetime"
                            }
                        }
                        newlist[0].substring(8, newlist[0].length) > now_day -> repeatBean.repNextCreatedTime = "${newlist[1]} $datetime"
                        else -> repeatBean.repNextCreatedTime = "${newlist[0]} $datetime"
                    }
                } else {
                    if (time_to <= time_form) {
                        calender.add(Calendar.DATE, +1)
                        if (calender.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
                            calender.add(Calendar.DATE, +1)
                        }
                        if (calender.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
                            calender.add(Calendar.DATE, +2)
                        }
                    }
                    repeatBean.repNextCreatedTime = "${day_format.format(calender.time)} $datetime"
                }
                newlist.mapIndexed { index, s ->
                    if (index > 0) {
                        sevenWorkTime.add("$s $datetime")
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return repeatBean
        }

        /**
         * 每周
         */
        fun weekChildAlarmDate(dateTime: String, repTypeParameter: String,repDisplayTime: String): RepeatBean {
            var repeatBean = RepeatBean()
            try {
                var calender = Calendar.getInstance()
                var week = if (repTypeParameter.contains("星期"))
                    repTypeParameter.substring(2) else repTypeParameter.substring(0)

                var week_number = when (week) {
                    "一" -> 1
                    "二" -> 2
                    "三" -> 3
                    "四" -> 4
                    "五" -> 5
                    "六" -> 6
                    "日" -> 7
                    else -> if (week.toInt() == 7) 0 else week.toInt()
                }

                val nowWeek = calender[Calendar.DAY_OF_WEEK] - 1

                val date = Date(System.currentTimeMillis())

                if (nowWeek == week_number) {
                    val time_form = simpleDateFormat.parse(simpleDateFormat.format(date)).time
                    var time_to = simpleDateFormat.parse(dateTime).time
                    if (time_to <= time_form) {
                        calender.add(Calendar.DATE, +7)
                    }
                } else if (nowWeek < week_number) {
                    calender.add(Calendar.DATE, +(week_number - nowWeek))
                } else {
                    calender.add(Calendar.DATE, +(7 - (nowWeek - week_number)))
                }

                var datetime = dateTime
                if (repDisplayTime == "0") {
                    datetime = "23:59"
                }
                repeatBean.repNextCreatedTime = "${day_format.format(calender.time)} $datetime"
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return repeatBean
        }

        /**
         * 每月，31 月底， 30 2月月底
         */
        fun monthChildAlarmDate(dateTime: String, repTypeParameter: String,repDisplayTime: String): RepeatBean {
            var repeatBean = RepeatBean()
            try {
                var calender = Calendar.getInstance()
                var day_number = if (repTypeParameter.contains("日")) repTypeParameter.substring(0, repTypeParameter.length - 1).toInt() else repTypeParameter.toInt()

                val now_year = calender.get(Calendar.YEAR)
                val now_month = calender.get(Calendar.MONTH) + 1
                val now_day = calender.get(Calendar.DATE)

                //是否闰年
                var isLeap = (now_year % 4 == 0 && now_year % 100 != 0 || now_year % 400 == 0)
                var datetime = dateTime
                if (repDisplayTime == "0") {
                    datetime = "23:59"
                }
                when {
                    day_number > now_day -> {
//                        calender.add(Calendar.MONTH, +1)
                        calender.set(Calendar.DATE, day_number)
                        val next_month = calender.get(Calendar.MONTH) + 1
                        val next_month_days = calender.getActualMaximum(Calendar.DAY_OF_MONTH)
                        if (next_month == 2 && (day_number == 30 || day_number == 31)) {
                            calender.set(Calendar.DATE, next_month_days)
                        }
                        repeatBean.repNextCreatedTime = "${day_format.format(calender.time)} $datetime"

                    }
                    day_number < now_day -> {
                        calender.add(Calendar.MONTH, +1)
                        calender.set(Calendar.DATE, day_number)
                        repeatBean.repNextCreatedTime = "${day_format.format(calender.time)} $datetime"
                    }
                    else -> {
                        val time_form = simpleDateFormat.parse(simpleDateFormat.format(Date(System.currentTimeMillis()))).time
                        var time_to = simpleDateFormat.parse(dateTime).time
                        if (time_to <= time_form) {
                            calender.add(Calendar.MONTH, +1)
                            calender.set(Calendar.DATE, day_number)
                            val next_month = calender.get(Calendar.MONTH) + 1
                            val next_month_days = calender.getActualMaximum(Calendar.DAY_OF_MONTH)
                            if (next_month == 2 && (day_number == 30 || day_number == 31)) {
                                calender.set(Calendar.DATE, next_month_days)
                            }
                        }
                        repeatBean.repNextCreatedTime = "${day_format.format(calender.time)} $datetime"
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return repeatBean
        }

        /**
         * 每年，响铃按照子记事响铃
         */
        fun yearChildAlarmDate(dateTime: String, repTypeParameter: String, yearType: String,repDisplayTime: String): RepeatBean {
            var repeatBean = RepeatBean()
            var calender = Calendar.getInstance()
            val now_year = calender.get(Calendar.YEAR)
            val now_month = calender.get(Calendar.MONTH) + 1
            val now_day = calender.get(Calendar.DATE)
            var next_isLeap = false
            var datetime = dateTime
            if (repDisplayTime == "0") {
                datetime = "23:59"
            }
            when (yearType) {
                "0" -> {
                    val month = repTypeParameter.split('-')[0].toInt()
                    val day = repTypeParameter.split('-')[1].toInt()

                    when {
                        month > now_month -> {
                            repeatBean.repNextCreatedTime = "$now_year-$repTypeParameter $datetime"
                        }
                        month == now_month -> {
                            when {
                                day > now_day -> {
                                    repeatBean.repNextCreatedTime = "$now_year-$repTypeParameter $datetime"
                                }
                                day == now_day -> {
                                    val time_form = simpleDateFormat.parse(simpleDateFormat.format(Date(System.currentTimeMillis()))).time
                                    var time_to = simpleDateFormat.parse(dateTime).time
                                    if (time_to <= time_form) {
                                        calender.add(Calendar.YEAR, +1)
                                        calender.set(Calendar.MONTH, month - 1)
                                        val next_year = calender.get(Calendar.YEAR)
                                        //当年是闰年，闹钟为2月29,明年设置为28
                                        next_isLeap = (next_year % 4 == 0 && next_year % 100 != 0 || next_year % 400 == 0)
                                        if (!next_isLeap && month == 2 && day == 29) {
                                            calender.set(Calendar.DATE, 28)
                                        } else {
                                            calender.set(Calendar.DATE, day)
                                        }
                                        repeatBean.repNextCreatedTime = "${day_format.format(calender.time)} $datetime"
                                    } else {
                                        repeatBean.repNextCreatedTime = "$now_year-$repTypeParameter $datetime"
                                    }
                                }
                                else -> {
                                    calender.add(Calendar.YEAR, +1)
                                    calender.set(Calendar.MONTH, month - 1)
                                    val next_year = calender.get(Calendar.YEAR)
                                    next_isLeap = (next_year % 4 == 0 && next_year % 100 != 0 || next_year % 400 == 0)
                                    if (!next_isLeap && month == 2 && day == 29) {
                                        calender.set(Calendar.DATE, 28)
                                    } else {
                                        calender.set(Calendar.DATE, day)
                                    }
                                    repeatBean.repNextCreatedTime = "${day_format.format(calender.time)} $datetime"
                                }
                            }
                        }
                        else -> {
                            calender.add(Calendar.YEAR, +1)
                            calender.set(Calendar.MONTH, month - 1)
                            val next_year = calender.get(Calendar.YEAR)
                            next_isLeap = (next_year % 4 == 0 && next_year % 100 != 0 || next_year % 400 == 0)
                            if (!next_isLeap && month == 2 && day == 29) {
                                calender.set(Calendar.DATE, 28)
                            } else {
                                calender.set(Calendar.DATE, day)
                            }
                            repeatBean.repNextCreatedTime = "${day_format.format(calender.time)} $datetime"
                        }
                    }
                }
                "1" -> {
                    val n_month = repTypeParameter.replace("1", "").replace("十一月", "冬月").replace("十二月", "腊月")
                    val list = App.getDBcApplication().queryNearLunartoSolarList(n_month)
                    if (list.size > 0) {
                        val n_calender = list[0]["calendar"] as String
                        val n_year = n_calender.split('-')[0].toInt()
                        val n_month = n_calender.split('-')[1].toInt()
                        val n_day = n_calender.split('-')[2].toInt()
                        when {
                            n_year > now_year -> {
                                repeatBean.repNextCreatedTime = "${list[0]["calendar"]} $datetime"
                            }
                            n_year == now_year -> {
                                when {
                                    n_month > now_month -> {
                                        repeatBean.repNextCreatedTime = "${list[0]["calendar"]} $datetime"
                                    }
                                    n_month == now_month -> {
                                        when {
                                            n_day > now_day -> {
                                                repeatBean.repNextCreatedTime = "${list[0]["calendar"]} $datetime"
                                            }
                                            n_day == now_day -> {
                                                val time_form = simpleDateFormat.parse(simpleDateFormat.format(Date(System.currentTimeMillis()))).time
                                                var time_to = simpleDateFormat.parse(dateTime).time
                                                if (time_to <= time_form) {
                                                    if (list.size > 1) {
                                                        repeatBean.repNextCreatedTime = "${list[1]["calendar"]} $datetime"
                                                    }
                                                } else {
                                                    repeatBean.repNextCreatedTime = "${list[0]["calendar"]} $datetime"
                                                }
                                            }
                                            else -> {
                                                if (list.size > 1) {
                                                    repeatBean.repNextCreatedTime = "${list[1]["calendar"]} $datetime"
                                                }
                                            }
                                        }
                                    }
                                    else -> {
                                        if (list.size > 1) {
                                            repeatBean.repNextCreatedTime = "${list[1]["calendar"]} $datetime"
                                        }
                                    }
                                }
                            }
                            else -> {
                                if (list.size > 1) {
                                    repeatBean.repNextCreatedTime = "${list[1]["calendar"]} $datetime"
                                }
                            }
                        }
                    } else {
                        repeatBean.repNextCreatedTime = "${day_format.format(calender.time)} $dateTime"
                    }
                }
            }
            return repeatBean
        }
    }

}